package com.siwei.mes.service.laboratory.factory.material.fine;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.fineAggregate.FineAggregateSfx;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.fineAggregate.DataFineAggregateKljp;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.FineLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 细骨料-筛分析
 *
 * @Description: 细骨料-筛分析
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 21:31
 */
@Service
public class FineSfxFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private FineLaboratoryMapper fineLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_SFX;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【细骨料-{}】", testProjectEnum.getName());
        //将json转成对象
        FineAggregateSfx fineSfx = objJson.toJavaObject(FineAggregateSfx.class);
        if (fineSfx == null) {
            log.info("细骨料-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }
        DataFineAggregateKljp dataFineKljp = new DataFineAggregateKljp();

        dataFineKljp.setS1(NullUtils.ifNull(fineSfx.getHgsfhsyzl()));
        dataFineKljp.setS2(NullUtils.ifNull(fineSfx.getYsklzl10()));
        dataFineKljp.setS3(NullUtils.ifNull(fineSfx.getYsklhl10()));
        dataFineKljp.setS4(NullUtils.ifNull(fineSfx.getDyfsyzl()));
        dataFineKljp.setS27(NullUtils.ifNull(fineSfx.getDefsyzl()));
        List<FineAggregateSfx.SfxInfo> sfxInfo = fineSfx.getSfxInfo();
        if (CollectionUtil.isNotEmpty(sfxInfo)) {
            if (!sfxInfo.isEmpty()) {
                FineAggregateSfx.SfxInfo sfxInfoOne = sfxInfo.get(0);
                if (sfxInfoOne != null) {
                    dataFineKljp.setS5(NullUtils.ifNull(sfxInfoOne.getSyl1()));
                    dataFineKljp.setS6(NullUtils.ifNull(sfxInfoOne.getFjsy1()));
                    dataFineKljp.setS7(NullUtils.ifNull(sfxInfoOne.getLjsy1()));

                    dataFineKljp.setS28(NullUtils.ifNull(sfxInfoOne.getSyl2()));
                    dataFineKljp.setS29(NullUtils.ifNull(sfxInfoOne.getFjsy2()));
                    dataFineKljp.setS30(NullUtils.ifNull(sfxInfoOne.getLjsy2()));

                    dataFineKljp.setS51(NullUtils.ifNull(sfxInfoOne.getLjsyppjz()));
                }
            }

            if (sfxInfo.size() > 1) {
                FineAggregateSfx.SfxInfo sfxInfoTwo = sfxInfo.get(1);
                if (sfxInfoTwo != null) {
                    dataFineKljp.setS8(NullUtils.ifNull(sfxInfoTwo.getSyl1()));
                    dataFineKljp.setS9(NullUtils.ifNull(sfxInfoTwo.getFjsy1()));
                    dataFineKljp.setS10(NullUtils.ifNull(sfxInfoTwo.getLjsy1()));

                    dataFineKljp.setS31(NullUtils.ifNull(sfxInfoTwo.getSyl2()));
                    dataFineKljp.setS32(NullUtils.ifNull(sfxInfoTwo.getFjsy2()));
                    dataFineKljp.setS33(NullUtils.ifNull(sfxInfoTwo.getLjsy2()));

                    dataFineKljp.setS52(NullUtils.ifNull(sfxInfoTwo.getLjsyppjz()));
                }
            }

            if (sfxInfo.size() > 2) {
                FineAggregateSfx.SfxInfo sfxInfoThree = sfxInfo.get(2);
                if (sfxInfoThree != null) {
                    dataFineKljp.setS11(NullUtils.ifNull(sfxInfoThree.getSyl1()));
                    dataFineKljp.setS12(NullUtils.ifNull(sfxInfoThree.getFjsy1()));
                    dataFineKljp.setS13(NullUtils.ifNull(sfxInfoThree.getLjsy1()));

                    dataFineKljp.setS34(NullUtils.ifNull(sfxInfoThree.getSyl2()));
                    dataFineKljp.setS35(NullUtils.ifNull(sfxInfoThree.getFjsy2()));
                    dataFineKljp.setS36(NullUtils.ifNull(sfxInfoThree.getLjsy2()));

                    dataFineKljp.setS53(NullUtils.ifNull(sfxInfoThree.getLjsyppjz()));
                }
            }

            if (sfxInfo.size() > 3) {
                FineAggregateSfx.SfxInfo sfxInfoFour = sfxInfo.get(3);
                if (sfxInfoFour != null) {
                    dataFineKljp.setS14(NullUtils.ifNull(sfxInfoFour.getSyl1()));
                    dataFineKljp.setS15(NullUtils.ifNull(sfxInfoFour.getFjsy1()));
                    dataFineKljp.setS16(NullUtils.ifNull(sfxInfoFour.getLjsy1()));

                    dataFineKljp.setS37(NullUtils.ifNull(sfxInfoFour.getSyl2()));
                    dataFineKljp.setS38(NullUtils.ifNull(sfxInfoFour.getFjsy2()));
                    dataFineKljp.setS39(NullUtils.ifNull(sfxInfoFour.getLjsy2()));

                    dataFineKljp.setS54(NullUtils.ifNull(sfxInfoFour.getLjsyppjz()));
                }
            }

            if (sfxInfo.size() > 4) {
                FineAggregateSfx.SfxInfo sfxInfoFive = sfxInfo.get(4);
                if (sfxInfoFive != null) {
                    dataFineKljp.setS17(NullUtils.ifNull(sfxInfoFive.getSyl1()));
                    dataFineKljp.setS18(NullUtils.ifNull(sfxInfoFive.getFjsy1()));
                    dataFineKljp.setS19(NullUtils.ifNull(sfxInfoFive.getLjsy1()));

                    dataFineKljp.setS40(NullUtils.ifNull(sfxInfoFive.getSyl2()));
                    dataFineKljp.setS41(NullUtils.ifNull(sfxInfoFive.getFjsy2()));
                    dataFineKljp.setS42(NullUtils.ifNull(sfxInfoFive.getLjsy2()));

                    dataFineKljp.setS55(NullUtils.ifNull(sfxInfoFive.getLjsyppjz()));
                }
            }

            if (sfxInfo.size() > 5) {
                FineAggregateSfx.SfxInfo sfxInfoSix = sfxInfo.get(5);
                if (sfxInfoSix != null) {
                    dataFineKljp.setS20(NullUtils.ifNull(sfxInfoSix.getSyl1()));
                    dataFineKljp.setS21(NullUtils.ifNull(sfxInfoSix.getFjsy1()));
                    dataFineKljp.setS22(NullUtils.ifNull(sfxInfoSix.getLjsy1()));

                    dataFineKljp.setS43(NullUtils.ifNull(sfxInfoSix.getSyl2()));
                    dataFineKljp.setS44(NullUtils.ifNull(sfxInfoSix.getFjsy2()));
                    dataFineKljp.setS45(NullUtils.ifNull(sfxInfoSix.getLjsy2()));

                    dataFineKljp.setS56(NullUtils.ifNull(sfxInfoSix.getLjsyppjz()));
                }
            }

            if (sfxInfo.size() > 6) {
                FineAggregateSfx.SfxInfo sfxInfoSeven = sfxInfo.get(6);
                if (sfxInfoSeven != null) {
                    dataFineKljp.setS23(NullUtils.ifNull(sfxInfoSeven.getSyl1()));
                    dataFineKljp.setS24(NullUtils.ifNull(sfxInfoSeven.getFjsy1()));
                    dataFineKljp.setS25(NullUtils.ifNull(sfxInfoSeven.getLjsy1()));

                    dataFineKljp.setS46(NullUtils.ifNull(sfxInfoSeven.getSyl2()));
                    dataFineKljp.setS47(NullUtils.ifNull(sfxInfoSeven.getFjsy2()));
                    dataFineKljp.setS48(NullUtils.ifNull(sfxInfoSeven.getLjsy2()));

                    dataFineKljp.setS57(NullUtils.ifNull(sfxInfoSeven.getLjsyppjz()));
                }
            }
        }
        dataFineKljp.setS26(NullUtils.ifNull(fineSfx.getXdms1()));
        dataFineKljp.setS49(NullUtils.ifNull(fineSfx.getXdms2()));
        dataFineKljp.setS50(NullUtils.ifNull(fineSfx.getXdmspjz()));

        dataFineKljp.setConclusion(fineSfx.getDxjl());
        dataFineKljp.setJPQ(fineSfx.getDxjl());
        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataFineKljp, "骨料检测室", fineSfx.getJcrq(), detail);

        //根据样品编码查询细骨料筛分析
        Map<String, Object> data_jgcl_ss_sdsfxBySampleNo = fineLaboratoryMapper.findDATA_JGCL_SS_SDSFXBySampleNo(sampleNo);
        //查询没值说明需要  新增细骨料筛分析
        if (data_jgcl_ss_sdsfxBySampleNo == null) {
            fineLaboratoryMapper.addDATA_JGCL_SS_SDSFX(dataFineKljp);
        } else {
            //修改细骨料筛分析
            fineLaboratoryMapper.updateDATA_JGCL_SS_SDSFX(dataFineKljp);
        }


        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }

        for (String str : set) {
            DataDefaultUc defaultUc = new DataDefaultUc();

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            String jcrq = fineSfx.getJcrq();

            defaultUc.setConclusion(fineSfx.getDxjl());
            defaultUc.setUcResultValue(fineSfx.getDxjl());
            defaultUc.setUcTestValue(fineSfx.getXdmspjz());


            //获取标准值
            for (CheckBatchConfig projectInfo : batchConfigList) {
                if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_SFX.getCode())) {
                    defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                }
            }

            //根据物料信息设置判断配置
            for (TestProjectSpecConfig test : testProjectSpecConfigList) {
                if (TestProjectEnum.FINE_AGGREGATE_PARAM_XGL_SFX.getCode().equals(test.getTestProjectCode())) {
                    if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                        String json = test.getObjJson();
                        super.setUcStandardValue(defaultUc, json, "sfx");
                    }
                }
            }

            //赋值
            super.setDefUc(defaultUc, experiment, "骨料检测室", sampleNo, jcrq, detail);

            defaultUc.setUcParameterID(parameterID);//项目id

            //新增或修改DataDefaultUc
            super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载协数据到品控：【细骨料-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        //将json转成对象
        FineAggregateSfx fineAggregateSfx = objJson.toJavaObject(FineAggregateSfx.class);
        if (fineAggregateSfx == null) {
            log.info("【细骨料-{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }
        //根据样品编码查询细骨料筛分析
        Map<String, Object> data = fineLaboratoryMapper.findDATA_JGCL_SS_SDSFXBySampleNo(sampleNo);
        if (data == null) {
            log.info("根据样品编码查询细骨料筛分析为空，跳过下载！sampleNo：{}", sampleNo);
            return null;
        }
        FineAggregateSfx.setValue(fineAggregateSfx, data);
        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(fineAggregateSfx);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.get("Equipment")));
        detail.setTemperature(NullUtils.ifNull(data.get("Temperature")));
        detail.setHumidness(NullUtils.ifNull(data.get("Humidity")));
        detail.setExperimentGist(NullUtils.ifNull(data.get("DetectonRuleCode")));
        detail.setJudgeGist(NullUtils.ifNull(data.get("AccessRuleCode")));

        experimentDetailMapper.updateByPrimaryKeySelective(detail);
        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
